package sso.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import sso.util.JwtUtils;
import sso.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

 @Bean
 public BCryptPasswordEncoder passwordEncoder(){
  return new BCryptPasswordEncoder();
 };

 @Override
 protected void configure(HttpSecurity http) throws Exception{
  http.csrf().disable();
  http.formLogin().successHandler(successHandler()).failureHandler(failureHandler());
  http.exceptionHandling().authenticationEntryPoint(entryPoint());
  http.authorizeRequests().anyRequest().authenticated();
 }

 private AuthenticationSuccessHandler successHandler(){
  return (httpServletRequest,httpServletResponse,authentication)->{
   Map<String,Object> map=new HashMap<>();
   map.put("state",200);
   map.put("message","login ok");
   Map<String,Object> jwtMap=new HashMap<>();
  User user=(User)authentication.getPrincipal();
  jwtMap.put("username",user.getUsername());
  List<String> authorities=new ArrayList<>();
   Collection<GrantedAuthority> aa=user.getAuthorities();
   for(GrantedAuthority a:aa){
    authorities.add(a.getAuthority());
   }
//   user.getAuthorities().forEach((authority)->{
//   authorities.add(authority.getAuthority());
//  });
   jwtMap.put("authorities",authorities);
   String token=JwtUtils.generatorToken(jwtMap);
   map.put("token",token);
   WebUtils.writeJsonToClient(httpServletResponse,map);
  };
 }

 private AuthenticationFailureHandler failureHandler(){
  return (httpServletRequest,httpServletResponse,authentication)->{
   Map<String,Object> map=new HashMap<>();
   map.put("state",500);
   map.put("message","username or password error");
   WebUtils.writeJsonToClient(httpServletResponse,map);
  };
 }

 private AuthenticationEntryPoint entryPoint(){
  return  (httpServletRequest,httpServletResponse,authentication)->{
   Map<String,Object> map=new HashMap<>();
   map.put("state",HttpServletResponse.SC_UNAUTHORIZED);
   map.put("message","请先登录再访问");
   WebUtils.writeJsonToClient(httpServletResponse,map);
  };
 }

}
